//
//  HAHoemAgentSubVC.m
//  HA
//
//  Created by sy on 2023/12/17.
//

#import "HAHoemAgentSubVC.h"
#import "HAHoemAgentSubCell.h"
#import "HAHoemAgentListModel.h"
#import "HAHoemAgentMakeCashBackVC.h"
#import "HAHoemAgentDetailsVC.h"
#import "HAHomeAgentScreenPopView.h"
#import "HAHoemAgentMakeShareMoneyPopView.h"
#import "HAAgentLevelsMo.h"
#import "HAWebVC.h"

@interface HAHoemAgentSubVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
/***/
@property (nonatomic, strong) UITextField *seachField;
/***/
@property (nonatomic, strong) UILabel *totalLabel;
/***/
@property (nonatomic, strong) NSString *keyword;
/***/
@property (nonatomic, strong) NSString *start;
/***/
@property (nonatomic, strong) NSString *end;
/***/
@property (nonatomic, strong) NSString *level;
/***/
@property (nonatomic, strong) NSMutableArray *agentLevelList;


@end

@implementation HAHoemAgentSubVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    self.view.backgroundColor = [UIColor khaBGColor];
    
    MJRefreshGifHeader *mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header = mj_header;
    
    MJRefreshBackGifFooter *mj_footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(laodMoreData)];
    self.tableView.mj_footer = mj_footer;
    
    [self.tableView.mj_header beginRefreshing];

    [self loadAgentlevels];

    // Do any additional setup after loading the view.
}

-(void)setupUI {
    
    UIView *seachBgView = [UIView ha_createView];
    seachBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:seachBgView];
    [seachBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_offset(44);
    }];
    
    UIButton *moreBtn = [[UIButton alloc]init];
    [moreBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];

    UIButton *seachBtn = [[UIButton alloc]init];
    [seachBtn setImage:[UIImage imageNamed:@"ha_searchIcon"] forState:UIControlStateNormal];
    [seachBtn addTarget:self action:@selector(seachBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:seachBtn];
    [seachBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(moreBtn.mas_left).offset(-5);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(22);
        make.height.mas_offset(22);
    }];

    UITextField *seachField = [[UITextField alloc]init];
    self.seachField = seachField;
    seachField.delegate = self;
    seachField.placeholder = @"输入代理名称/手机号";
    seachField.font = [UIFont systemFontOfSize:18];
    seachField.returnKeyType = UIReturnKeySearch;
    [seachBgView addSubview:seachField];
    [seachField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.equalTo(seachBtn.mas_left).offset(-15);
        make.centerY.mas_equalTo(0);
        make.height.equalTo(@32);
    }];
    
    self.totalLabel = [UILabel ha_BLabelWithFont:14 textColor:@"#000000" text:@"总计: 0" alignment:2];
    [self.view addSubview:self.totalLabel];
    [self.totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.left.mas_equalTo(15);
        make.height.mas_offset(28);
        make.top.mas_equalTo(54);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(54+28+2);
        make.bottom.mas_equalTo(0);
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54 + 92;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WS(weakSelf)
    HAHoemAgentSubCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHHoemAgentSubCellID"];
    if (!cell) {
        cell = [[HAHoemAgentSubCell alloc]initWithStyle:0 reuseIdentifier:@"YHHoemAgentSubCellID"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.isCanPhone = [self.source_id isEqualToString:@"1"];
    cell.model = self.dataArray[indexPath.row];
    cell.YHHoemAgentSubCellBt1CBlock = ^(HAHoemAgentListModel * _Nonnull mo) {
//        YHHoemAgentMakeCashBackViewController *vc = [[YHHoemAgentMakeCashBackViewController alloc]init];
//        vc.agent_id = mo.ID;
//        [weakSelf.navigationController pushViewController:vc animated:YES];
        HAWebVC *vc = [[HAWebVC alloc]init];
        vc.tit = @"返现规则";
        vc.urlStr = [NSString stringWithFormat:@"%@index/reward/index.html?agent_id=%@&token=%@",kHaBaseUrl,mo.ID,HAUserDefaults.token];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.YHHoemAgentSubCellBt2CBlock = ^(HAHoemAgentListModel * _Nonnull mo) {
        [weakSelf loadAgentlevelsMake:mo.ID];
    };
    return cell;
}

-(void)loadAgentlevelsMake:(NSString *)agent_id {
    WS(weakSelf)
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"v1/agent/levels?agent_id=%@",agent_id];
    request1.requestMethod = SYRequestMethodGET;
    [MBProgressHUD showLoading:self.view];
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.code == 1) {
                NSArray *array = [HAAgentLevelsMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                HAHoemAgentMakeShareMoneyPopView *menu = [[HAHoemAgentMakeShareMoneyPopView alloc]initWithList:array];
                [menu show];
                menu.YHChooseTabMenuCellSureBlock = ^(HAAgentLevelsMo * _Nonnull mo) {
                    [weakSelf makeAgentlevelsMake:agent_id mo:mo];
                };
            }
        }
    }];
}

//http:wap.yinhui.net.cn/index/reward/index.html?agent_id=xxxx&token=xxxx
//      RequestParams: agent_id=10689,level=2
-(void)makeAgentlevelsMake:(NSString *)agent_id mo:(HAAgentLevelsMo *)mo {
    NSDictionary *dic = @{
        @"agent_id" : agent_id?:@"",
        @"level" : mo.level ?: @"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"v1/agent/levels"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dic;
    [MBProgressHUD showLoading:self.view];
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.code == 1) {
                [MBProgressHUD showSuccess:@"修改成功"];
                [self.tableView.mj_header beginRefreshing];
            }else {
                [MBProgressHUD showError:@"修改失败"];
            }
        }
    }];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.seachField isFirstResponder]) {
        [self.seachField resignFirstResponder];
        return;
    }
    HAHoemAgentListModel *model = self.dataArray[indexPath.row];
    HAHoemAgentDetailsVC *vc = [[HAHoemAgentDetailsVC alloc]init];
    vc.agent_id = model.ID;
    vc.name = model.name;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)seachBtnClick {
    self.keyword = self.seachField.text;
    [self.tableView.mj_header beginRefreshing];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self.view endEditing:YES];

    if (textField == self.seachField) {
        self.keyword = textField.text;
        [self.tableView.mj_header beginRefreshing];
    }
    

    return YES;
}

-(void)moreBtnClick {
    WS(weakSelf)
    HAHomeAgentScreenPopView *menu = [[HAHomeAgentScreenPopView alloc]init];
    menu.keyword = self.keyword;
    menu.start= self.start;
    menu.end = self.end;
    menu.agentLevelList = self.agentLevelList;
    [menu loadViews];
    [menu show];
    menu.YHHomeAgentScreenMenuViewBlock = ^(NSString * _Nonnull searchText, NSString * _Nonnull start, NSString * _Nonnull end) {
        weakSelf.seachField.text = searchText;
        weakSelf.start = start;
        weakSelf.end = end;
        weakSelf.keyword = searchText;
        NSString *level = @"";
        for (HAAgentLevelsMo *mo in weakSelf.agentLevelList) {
            if (mo.isSel == YES) {
                level = mo.level;
                break;
            }
        }
        weakSelf.level = level;
        [weakSelf.tableView.mj_header beginRefreshing];
    };

}

-(void)loadNewData {

    NSString *url = @"";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"10" forKey:@"pageSize"];
    [dict setValue:@"1" forKey:@"page"];
    [dict setValue:self.keyword?:@"" forKey:@"keyword"];
    [dict setValue:self.start ?:@"" forKey:@"start"];
    [dict setValue:self.end ?:@"" forKey:@"end"];
    [dict setValue:self.level ?:@"" forKey:@"level"];
    url = @"agent/items";
    if ([self.source_id isEqualToString:@"1"]) {
        [dict setValue:@"1" forKey:@"source_id"];
    }else if ([self.source_id isEqualToString:@"2"]) {
        [dict setValue:@"2" forKey:@"source_id"];
//        url = @"agent/index";
    }
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = url;
    request1.requestMethod = SYRequestMethodGET;
    request1.parms = dict;

    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_header endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [self.dataArray removeAllObjects];
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAHoemAgentListModel mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
                if ([[dataModel.data allKeys] containsObject:@"total"]) {
                    NSString *total = [NSString stringWithFormat:@"%@",dataModel.data[@"total"]];
                    self.totalLabel.text = [NSString stringWithFormat:@"总计: %@",total];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
            
        }
    }];
    
}

-(void)laodMoreData {
    
    NSInteger count = ceilf(self.dataArray.count*0.1)+1;
    NSString *pageNo = [NSString stringWithFormat:@"%ld",(long)count];
    
    NSString *url = @"";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:@"10" forKey:@"pageSize"];
    [dict setValue:pageNo forKey:@"page"];
    [dict setValue:self.keyword?:@"" forKey:@"keyword"];
    [dict setValue:self.start ?:@"" forKey:@"start"];
    [dict setValue:self.end ?:@"" forKey:@"end"];
    [dict setValue:self.level ?:@"" forKey:@"level"];
    url = @"agent/items";
    if ([self.source_id isEqualToString:@"1"]) {
        [dict setValue:@"1" forKey:@"source_id"];
    }else if ([self.source_id isEqualToString:@"2"]) {
        [dict setValue:@"2" forKey:@"source_id"];
//        url = @"agent/index";
    }
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = url;
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;

    [self.tableView.mj_footer beginRefreshing];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_footer endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAHoemAgentListModel mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
        }
    }];
    
}

-(void)loadAgentlevels {
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"v1/agent/levels?agent_id="];
    request1.requestMethod = SYRequestMethodGET;
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            if (dataModel.code == 1) {
                [self.agentLevelList removeAllObjects];
                NSArray *array = [HAAgentLevelsMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                [self.agentLevelList addObjectsFromArray:array];
            }
        }
    }];
}


- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (NSMutableArray *)agentLevelList
{
    if (!_agentLevelList) {
        _agentLevelList = [NSMutableArray array];
        
    }
    return _agentLevelList;
}

#pragma mark - 无数据处理 DZNEmptyDataSetSource DZNEmptyDataSetDelegate
//设置title
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无数据~";
    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#999999"]
    };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

//设置image
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"hl_nodata"];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return  YES;
}

@end
